//
//  BottomScrollView.swift
//  Game
//
//  Created by woniu on 2025/8/22.
//

import Foundation
import UIKit
import AudioToolbox


protocol BottomScrollViewDelegate: NSObjectProtocol {
    func onSelected(item:ScrollItem,view:BottomScrollView)
}


class BottomScrollView: UIView {
    weak var delegate:BottomScrollViewDelegate?
    
    public var dataArray:[ScrollItem] = []
    public var viewList:[CImageView] = []
    private var contentView:UIScrollView!
    private var leftButton:UIButton!
    private var rightButton:UIButton!
    private var currentIndex = 0
    private var itemCount = 0
    private var indexIconView:UIImageView!
    private var indexWordLab:UILabel!
    private var playSoundButton:UIButton!
    private var lastUpdateTime = 0
    
    override init(frame: CGRect){
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    public func getItemW()->CGFloat{
        return Utils.isPad() ? 120 : 70
    }
    
    public func getTotalW()->CGFloat{
        let itemW = getItemW()
        return itemW * CGFloat(5) + 90
    }
    
    private func setupUI(){
        self.backgroundColor = .black
        
        contentView = UIScrollView(frame: frame)
        if #available(iOS 11.0, *) {
            contentView.contentInsetAdjustmentBehavior = .never
        }
        contentView.showsVerticalScrollIndicator = false
        contentView.backgroundColor = .black
        contentView.isPagingEnabled = true
        contentView.isScrollEnabled = false
        contentView.showsHorizontalScrollIndicator = false
        self.addSubview(contentView)
        
        leftButton = UIButton(type: .custom)
        leftButton.setImage(UIImage(named: "向左_圆"), for:.normal)
        leftButton.imageView?.contentMode = .scaleAspectFit
        leftButton.addTarget(self, action: #selector(onClickLeft), for: .touchUpInside)
        self.addSubview(leftButton)
        
        rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "向右_圆"), for:.normal)
        rightButton.imageView?.contentMode = .scaleAspectFit
        rightButton.addTarget(self, action: #selector(onClickRight), for: .touchUpInside)
        self.addSubview(rightButton)
        
        indexIconView = UIImageView()
        indexIconView.image = UIImage(named: "箭头_向下")
        indexIconView.contentMode = .scaleAspectFit
        self.addSubview(indexIconView)
        
        indexWordLab = UILabel()
        indexWordLab.textColor = .white
        if Utils.isPad(){
            indexWordLab.font = UIFont.boldSystemFont(ofSize: 35)
        }else{
            indexWordLab.font = UIFont.systemFont(ofSize: 20)
        }
        indexWordLab.layer.cornerRadius = 5
        indexWordLab.layer.borderColor = UIColor.white.cgColor
        indexWordLab.layer.borderWidth = 1
        indexWordLab.layer.masksToBounds = true
        indexWordLab.textAlignment = .center
        self.addSubview(indexWordLab)
        
        playSoundButton = UIButton(type: .custom)
        playSoundButton.imageView?.contentMode = .scaleAspectFit
        playSoundButton.setImage(UIImage(named: "播放语音"), for: .normal)
        playSoundButton.addTarget(self, action: #selector(onPlaySound), for:.touchUpInside)
        self.addSubview(playSoundButton)
    }
    
    public func update(by dataSource:[ScrollItem],defaultSelectedIndex:Int){
        self.dataArray = dataSource
        itemCount = dataSource.count
        for view in viewList{view.removeFromSuperview()}
        viewList.removeAll()
        
        for item in dataSource{
            let itemView = CImageView(frame: .zero)
            itemView.update(item: item)
            itemView.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
            itemView.addGestureRecognizer(tap)
            contentView.addSubview(itemView)
            viewList.append(itemView)
            if item.index == defaultSelectedIndex{
                self.currentIndex = item.index
            }
        }
        showResultWord(indexVal: self.currentIndex)
        self.setNeedsLayout()
        
    }
    
    @objc func onTap(_ deco:UITapGestureRecognizer){
        if let tarGetView = deco.view as? CImageView{
            let targetIndex = tarGetView.tag
            if targetIndex > currentIndex{
                moveToLeft(toIndex: targetIndex)
            }else{
                moveToRight(toIndex: targetIndex)
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let iconH:CGFloat = 25
        let itemWidth = self.getItemW()
        let itemHeight = itemWidth
        let wordLabH:CGFloat = Utils.isPad() ? 80 : 40
        let wordLabW:CGFloat = Utils.isPad() ? 320 : 200
        indexWordLab.frame = CGRect(x:(self.width-wordLabW)*0.5, y: 0, width: wordLabW, height:wordLabH)
        playSoundButton.frame = CGRect(x:indexWordLab.frame.maxX+10, y:(indexWordLab.height-40)*0.5, width: 40, height:40)
        indexIconView.frame = CGRect(x:(self.width-iconH)*0.5, y:indexWordLab.frame.maxY, width: iconH, height: iconH)
        
        contentView.frame = CGRect(x: 45, y:indexIconView.frame.maxY, width: self.width-90, height:itemHeight)
        leftButton.frame = CGRect(x: 0, y:contentView.y, width: 40, height: contentView.height)
        rightButton.frame = CGRect(x: self.width-40, y: leftButton.y, width: leftButton.width, height: leftButton.height)
        
        var lastX:CGFloat = 0
        for view in viewList{
            view.frame = CGRect(x: lastX, y: 0, width:itemWidth, height: contentView.height)
            lastX = view.frame.maxX
        }
        contentView.contentSize = CGSize(width: lastX, height: contentView.height)
    }
    
    
    @objc func onClickLeft(){
        var toIndex = currentIndex - Int.random(in: 1...3)
        if toIndex < 0{
            toIndex = 0
        }
        if toIndex == currentIndex{
            print("没有了")
            return
        }
        moveToRight(toIndex: toIndex)
    }
    
    
    @objc func onClickRight(){
        
        var toIndex = currentIndex + Int.random(in: 1...3)
        if toIndex >= dataArray.count{
            toIndex = dataArray.count-1
        }
        if toIndex == currentIndex{
            print("没有了")
            return
        }
        moveToLeft(toIndex: toIndex)
    }
    
    //往左边移动（后退）
    private func moveToLeft(toIndex:Int){
        let itemW = getItemW()
        let moveCount:CGFloat = abs(CGFloat(currentIndex - toIndex))
        playSystemSound(playCount: Int(moveCount))
        self.currentIndex = toIndex
        
        UIView.animate(withDuration: moveCount * 0.3, delay: 0, options: [],animations: {
            let targetX:CGFloat = self.contentView.contentOffset.x + moveCount * itemW
            self.contentView.setContentOffset(CGPoint(x: targetX, y: 0), animated: false)
        }) { re in
            self.showResultWord(indexVal: toIndex)
        }
    }
    
    //往右边移动（前进）
    private func moveToRight(toIndex:Int){
        let itemW = getItemW()
        let moveCount:CGFloat = abs(CGFloat(toIndex - currentIndex))
        playSystemSound(playCount: Int(moveCount))
        self.currentIndex = toIndex
        print("最后选中:\(self.currentIndex)")
        
        UIView.animate(withDuration: moveCount * 0.3, delay: 0, options: [],animations: {
            let targetX:CGFloat = self.contentView.contentOffset.x - moveCount * itemW
            self.contentView.setContentOffset(CGPoint(x: targetX, y: 0), animated: false)
        }) { re in
            self.showResultWord(indexVal: toIndex)
        }
    }
    
    
    /// 更新结果
    private func showResultWord(indexVal:Int){
        for view in viewList{
            view.update(isSelected: false)
        }
        viewList[indexVal].update(isSelected: true)
        let item = dataArray[indexVal]
        indexWordLab.text = item.word
        delegate?.onSelected(item: item, view: self)
        
    }
    
    
    /// 播放音效
    /// - Parameter playCount: 播放次数
    private func playSystemSound(playCount:Int){
        let distance = Int(Date().timeIntervalSince1970) - lastUpdateTime
        //若在一秒之内，不进行播放，
        if distance <= 0{
            return
        }
        lastUpdateTime = Int(Date().timeIntervalSince1970)
        for i in 0..<playCount{
            let delay = TimeInterval(i) * 0.3
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                AudioServicesPlaySystemSound(1057)
            }
        }
    }
    
    //播放语音
    @objc func onPlaySound(){
        if dataArray.isEmpty{return}
        let item =  dataArray[currentIndex]
        Utils.play(word: item.word)
    }
}

class ScrollItem:WordItem{
    public var index = 0
    public var selected = false
}

class CImageView: UIView {
    public var iconView:UIImageView!
    private var coverView:UIView!
    
    override init(frame: CGRect){
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        self.backgroundColor = .black
        
        iconView = UIImageView()
        iconView.backgroundColor = .white
        iconView.contentMode = .scaleAspectFit
        iconView.layer.cornerRadius = 5
        iconView.layer.masksToBounds = true
        self.addSubview(iconView)
        
        coverView = UIView()
        coverView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        coverView.layer.cornerRadius = 5
        coverView.layer.masksToBounds = true
        coverView.isHidden = true
        self.addSubview(coverView)
    }
    
    public func update(item:ScrollItem){
        self.tag = item.index
        if let icon = item.image{
            iconView.image = icon
        }else if !item.imgName.isEmpty{
            let icon = GameManager.share.getImageBy(item.imgName)
            iconView.image = icon
            item.image = icon
        }
    }
    
    public func update(isSelected:Bool){
        coverView.isHidden = isSelected
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        iconView.frame = CGRect(x: 5, y: 0, width: self.width-10, height: self.height)
        coverView.frame = iconView.frame
    }
}
